//
//  LGNFilterAlertView.m
//  LGNnglishTeaching
//
//  Created by 刘亚军 on 2021/11/4.
//  Copyright © 2021 刘亚军. All rights reserved.
//

#import "LGNFilterAlertView.h"
#import "LGNClipView.h"
#import "LGNFilterCollectionViewCell.h"
#import "LGNFilterCollectionReusableView.h"
#import "LGNFilterFlowLayout.h"
#import "LGNFilterModel.h"
#import "LGKConst.h"
@interface LGNFilterAlertView ()<UICollectionViewDelegate,UICollectionViewDataSource,LGNFilterFlowLayoutDelegate>
@property (nonatomic,strong) UIView *maskView;
@property (nonatomic,strong) LGNClipView *bgClipView;
@property (nonatomic,strong) UILabel *titleL;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) UIButton *cancelBtn;
@property (nonatomic,strong) UIButton *sureBtn;
@end
@implementation LGNFilterAlertView
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.bgClipView];
        [self.bgClipView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        [self.bgClipView addSubview:self.titleL];
        [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.bgClipView);
            make.top.equalTo(self.bgClipView).offset(5);
            make.height.mas_equalTo(40);
            make.left.equalTo(self).offset(60);
        }];
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:LG_ColorWithHex(0x0077FF) forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_cancelBtn addTarget:self action:@selector(cancelClickAction) forControlEvents:UIControlEventTouchUpInside];
        
        _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_sureBtn setTitleColor:LG_ColorWithHex(0x0077FF) forState:UIControlStateNormal];
        _sureBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_sureBtn addTarget:self action:@selector(sureClickAction) forControlEvents:UIControlEventTouchUpInside];
        
        [self.bgClipView addSubview:self.sureBtn];
        [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.titleL);
            make.right.equalTo(self.bgClipView).offset(-2);
            make.width.mas_offset(50);
            make.height.mas_offset(28);
        }];
        [self.bgClipView addSubview:self.cancelBtn];
        [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.titleL);
            make.left.equalTo(self.bgClipView).offset(2);
            make.width.mas_offset(50);
            make.height.mas_offset(28);
        }];
        
        [self.bgClipView addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.left.equalTo(self.bgClipView);
            make.top.equalTo(self.titleL.mas_bottom);
            make.bottom.equalTo(self.bgClipView).offset(-[self yj_tabBarSpace]-20);
        }];
    }
    return self;
}

+ (LGNFilterAlertView *)filterAlertViewOnView:(UIView *)onView{
    CGFloat height = IsIPad ? 400 : LG_ScreenHeight*0.6;
    LGNFilterAlertView *alertView = [[LGNFilterAlertView alloc] initWithFrame:CGRectMake(0, LG_ScreenHeight, LG_ScreenWidth, height)];
    alertView.maskView = [[UIView alloc] initWithFrame:onView.bounds];
    alertView.maskView.backgroundColor = [UIColor colorWithWhite:0 alpha:1];
    alertView.maskView.alpha = 0;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:alertView action:@selector(hide)];
    [alertView.maskView addGestureRecognizer:tap];
    [onView addSubview:alertView.maskView];
    [onView addSubview:alertView];
    return alertView;
}
- (void)setTitleStr:(NSString *)titleStr{
    _titleStr = titleStr;
    self.titleL.text = titleStr;
}
- (void)setDataArr:(NSArray<LGNFilterModel *> *)dataArr{
    _dataArr = dataArr;
    [self.collectionView reloadData];
}
- (void)show{
    [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:.8 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.maskView.alpha = 0.6;
        self.transform = CGAffineTransformMakeTranslation(0, -self.height);
   } completion:^(BOOL isFinished) {
   }];
}
- (void)hide{
    [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:.8 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.transform = CGAffineTransformIdentity;
        self.maskView.alpha = 0;
   } completion:^(BOOL isFinished) {
       [self removeFromSuperview];
   }];
}
- (void)cancelClickAction{
    [self hide];
}
- (void)sureClickAction{
    NSArray *indexArr = [self.dataArr yj_map:^id _Nonnull(LGNFilterModel *object) {
        return @(object.SelIndex);
    }];
    if (self.delegate && [self.delegate respondsToSelector:@selector(LGNFilterAlertViewDidSelcetedItemAtIndexArr:)]) {
        [self.delegate LGNFilterAlertViewDidSelcetedItemAtIndexArr:indexArr];
    }
    [self hide];
}
#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataArr.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr[section].SelNames.count;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    LGNFilterCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([LGNFilterCollectionReusableView class]) forIndexPath:indexPath];
    headerView.titleStr =  self.dataArr[indexPath.section].Title;
    return headerView;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LGNFilterModel *model = self.dataArr[indexPath.section];
    LGNFilterCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LGNFilterCollectionViewCell class]) forIndexPath:indexPath];
    cell.text = model.SelNames[indexPath.item];
    cell.isChoice = model.SelIndex == indexPath.item;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    LGNFilterModel *model = self.dataArr[indexPath.section];
    LGNFilterCollectionViewCell *lastCell = (LGNFilterCollectionViewCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:model.SelIndex inSection:indexPath.section]];
    lastCell.isChoice = NO;
    LGNFilterCollectionViewCell *cell = (LGNFilterCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.isChoice = !cell.isChoice;
    model.SelIndex = indexPath.item;
}
#pragma mark - LGNFilterFlowLayoutDelegate
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(LGNFilterFlowLayout *)collectionViewLayout widthForItemAtIndexPath:(NSIndexPath *)indexPath{
    LGNFilterModel *model = self.dataArr[indexPath.section];
    NSString *str = model.SelNames[indexPath.item];
    CGSize stringSize = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:IsIPad ? 18 : 16]} context:nil].size;
    return stringSize.width+50;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(LGNFilterFlowLayout *)collectionViewLayout heightForHeaderAtIndexPath:(NSIndexPath *)indexPath{
    return 5;
}

- (UILabel *)titleL{
    if (!_titleL) {
        _titleL = [UILabel new];
        _titleL.text = @"筛选";
        _titleL.font = [UIFont systemFontOfSize:IsIPad ? 19 : 17 weight:UIFontWeightMedium];
        _titleL.textColor = LG_ColorWithHex(0x252525);
        _titleL.textAlignment = NSTextAlignmentCenter;
    }
    return _titleL;
}
- (UIButton *)cancelBtn{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:LG_ColorWithHex(0x009CFF) forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = LG_SysFont(16);
        [_cancelBtn addTarget:self action:@selector(cancelClickAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}
- (UIButton *)sureBtn{
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _sureBtn.titleLabel.font = LG_SysFont(16);
        [_sureBtn addTarget:self action:@selector(sureClickAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}
- (LGNClipView *)bgClipView{
    if (!_bgClipView) {
        _bgClipView = [[LGNClipView alloc] initWithFrame:CGRectZero];
        _bgClipView.backgroundColor = [UIColor whiteColor];
        _bgClipView.clipRadiu = 10;
        _bgClipView.clipDirections = @[@"TopLeft",@"TopRight"];
    }
    return _bgClipView;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat space = IsIPad ? 30 : 20;
        CGFloat itemSpacing = IsIPad ? 25 : 15;
        CGFloat itemW = IsIPad ? 100 : (LG_ScreenWidth - space*2-itemSpacing*2) / 3 - 1;
        layout.minimumInteritemSpacing = itemSpacing;
        layout.minimumLineSpacing = 15;
        layout.headerReferenceSize = CGSizeMake(LG_ScreenWidth, 45);
        layout.itemSize = CGSizeMake(itemW, IsIPad ? 40 : 36);
        layout.sectionInset = UIEdgeInsetsMake(0, space, 10, space);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView registerClass:[LGNFilterCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([LGNFilterCollectionViewCell class])];
        [_collectionView registerClass:[LGNFilterCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([LGNFilterCollectionReusableView class])];
    }
    return _collectionView;
}
@end
